package com.yunst.net.handle;

import com.yunst.net.message.EventMessage;
import com.yunst.net.message.ImageMessage;
import com.yunst.net.message.EventEnum;
import com.yunst.net.protocol.MessageDecode;
import com.yunst.net.protocol.MessageEncode;
import com.yunst.view.Window;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

/**
 * @author yunst
 * @date 2022/12/30
 */
public class ChannelInitializerHandle extends ChannelInitializer<NioSocketChannel> {
    public volatile static ChannelHandlerContext channelHandlerContext;

    protected void initChannel(NioSocketChannel channel) {
        channel.pipeline().addLast(new MessageDecode());
        channel.pipeline().addLast(new MessageEncode());
        channel.pipeline().addLast(new ChanelHandler());

        channel.pipeline().addLast(new SimpleChannelInboundHandler<ImageMessage>() {
            @Override
            public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
                Window.errorMessage();
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                Window.errorMessage();
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                System.out.println("连接成功");
                channelHandlerContext = ctx;
                String value = String.valueOf(EventEnum.START.getType());
                EventMessage eventMessage = new EventMessage();
                eventMessage.setLen(value.length());
                eventMessage.setContent(value.getBytes(StandardCharsets.UTF_8));
                ctx.writeAndFlush(eventMessage);
            }

            @Override
            protected void channelRead0(ChannelHandlerContext channelHandlerContext, ImageMessage imageMessage) throws Exception {
                System.out.println("接收到的内容：" + imageMessage.getContent().length);
                Window.setImage(imageMessage.getContent());

            }
        });

    }
}
